#!/usr/bin/env python3

import inspect
import logging
import optparse
import os
import sys
import tempfile
import unittest
from unittest import mock

localmodule = os.path.realpath(
    os.path.join(os.path.dirname(inspect.getfile(inspect.currentframe())), '..'))
if localmodule not in sys.path:
    sys.path.insert(0, localmodule)

import fdroidserver.common
import fdroidserver.server
from testcommon import TmpCwd


class ServerTest(unittest.TestCase):
    '''fdroidserver/server.py'''

    def setUp(self):
        logging.basicConfig(level=logging.DEBUG)
        self.basedir = os.path.join(localmodule, 'tests')

        fdroidserver.server.options = mock.Mock()
        fdroidserver.server.config = {}

    def test_update_serverwebroot_make_cur_version_link(self):

        # setup parameters for this test run
        fdroidserver.server.options.no_chcksum = True
        fdroidserver.server.options.identity_file = None
        fdroidserver.server.options.verbose = False
        fdroidserver.server.options.quiet = True
        fdroidserver.server.options.identity_file = None
        fdroidserver.server.config['make_current_version_link'] = True
        serverwebroot = "example.com:/var/www/fdroid"
        repo_section = 'repo'

        # setup function for asserting subprocess.call invocations
        call_iteration = 0

        def update_server_webroot_call(cmd):
            nonlocal call_iteration
            if call_iteration == 0:
                self.assertListEqual(cmd, ['rsync',
                                           '--archive',
                                           '--delete-after',
                                           '--safe-links',
                                           '--quiet',
                                           '--exclude', 'repo/index.xml',
                                           '--exclude', 'repo/index.jar',
                                           '--exclude', 'repo/index-v1.jar',
                                           'repo',
                                           'example.com:/var/www/fdroid'])
            elif call_iteration == 1:
                self.assertListEqual(cmd, ['rsync',
                                           '--archive',
                                           '--delete-after',
                                           '--safe-links',
                                           '--quiet',
                                           'repo',
                                           serverwebroot])
            elif call_iteration == 2:
                self.assertListEqual(cmd, ['rsync',
                                           '--archive',
                                           '--delete-after',
                                           '--safe-links',
                                           '--quiet',
                                           'Sym.apk',
                                           'Sym.apk.asc',
                                           'Sym.apk.sig',
                                           'example.com:/var/www/fdroid'])
            else:
                self.fail('unexpected subprocess.call invocation')
            call_iteration += 1
            return 0

        with tempfile.TemporaryDirectory() as tmpdir, TmpCwd(tmpdir):
            os.mkdir('repo')
            os.symlink('repo/com.example.sym.apk', 'Sym.apk')
            os.symlink('repo/com.example.sym.apk.asc', 'Sym.apk.asc')
            os.symlink('repo/com.example.sym.apk.sig', 'Sym.apk.sig')
            with mock.patch('subprocess.call', side_effect=update_server_webroot_call):
                fdroidserver.server.update_serverwebroot(serverwebroot,
                                                         repo_section)
        self.assertEqual(call_iteration, 3, 'expected 3 invocations of subprocess.call')

    def test_update_serverwebroot_with_id_file(self):

        # setup parameters for this test run
        fdroidserver.server.options.no_chcksum = False
        fdroidserver.server.options.verbose = True
        fdroidserver.server.options.quiet = False
        fdroidserver.server.options.identity_file = None
        fdroidserver.server.config['identity_file'] = './id_rsa'
        fdroidserver.server.config['make_current_version_link'] = False
        serverwebroot = "example.com:/var/www/fdroid"
        repo_section = 'archive'

        # setup function for asserting subprocess.call invocations
        call_iteration = 0

        def update_server_webroot_call(cmd):
            nonlocal call_iteration
            if call_iteration == 0:
                self.assertListEqual(cmd, ['rsync',
                                           '--archive',
                                           '--delete-after',
                                           '--safe-links',
                                           '--verbose',
                                           '-e',
                                           'ssh -oBatchMode=yes -oIdentitiesOnly=yes -i '
                                           + fdroidserver.server.config['identity_file'],
                                           '--exclude', 'archive/index.xml',
                                           '--exclude', 'archive/index.jar',
                                           '--exclude', 'archive/index-v1.jar',
                                           'archive',
                                           serverwebroot])
            elif call_iteration == 1:
                self.assertListEqual(cmd, ['rsync',
                                           '--archive',
                                           '--delete-after',
                                           '--safe-links',
                                           '--verbose',
                                           '-e',
                                           'ssh -oBatchMode=yes -oIdentitiesOnly=yes -i '
                                           + fdroidserver.server.config['identity_file'],
                                           'archive',
                                           serverwebroot])
            else:
                self.fail('unexpected subprocess.call invocation')
            call_iteration += 1
            return 0

        with mock.patch('subprocess.call', side_effect=update_server_webroot_call):
            fdroidserver.server.update_serverwebroot(serverwebroot,
                                                     repo_section)
        self.assertEqual(call_iteration, 2, 'expected 2 invocations of subprocess.call')


if __name__ == "__main__":
    os.chdir(os.path.dirname(__file__))

    parser = optparse.OptionParser()
    parser.add_option("-v", "--verbose", action="store_true", default=False,
                      help="Spew out even more information than normal")
    (fdroidserver.common.options, args) = parser.parse_args(['--verbose'])

    newSuite = unittest.TestSuite()
    newSuite.addTest(unittest.makeSuite(ServerTest))
    unittest.main(failfast=False)
